package com.future.platform.common.service.impl;

import com.future.platform.common.entity.ConfigInterface;
import com.future.platform.common.entity.PlatformResponse;
import com.future.platform.common.runner.PlatformStartUpRunner;
import com.future.platform.common.service.InvokeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lijihong
 * @date 2021/1/14
 */
@Slf4j
@Service
public class InvokeServiceImpl implements InvokeService {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public PlatformResponse invoke(String interfaceName, Map<String, Object> params){
        //获取接口信息
        log.info(interfaceName);
        ConfigInterface configInterface = PlatformStartUpRunner.interfaceMap.get(interfaceName);
        //处理入参
        PlatformResponse res = new PlatformResponse().success();
        List<Object> p = new ArrayList<>();
        for (String s : configInterface.getInputParam().split(",")){
            p.add(params.get(s));
        }
        /**
         * 判断是否是本系统的数据源，如果是就直接执行语句
         * 如果不是，查找到对应的数据源执行语句
         * datasourceId为空则为本系统数据源
         */
        if (null == configInterface.getDatasourceId()){
            byCaseInvoke(jdbcTemplate, configInterface.getContent(),
                    p.toArray(), configInterface.getType(), res);
        }else{
            JdbcTemplate j = PlatformStartUpRunner.datasource.get(configInterface.getDatasourceId());
            byCaseInvoke(j, configInterface.getContent(),
                    p.toArray(), configInterface.getType(), res);
        }
        return res;
    }

    /**
     * 根据type选择是查询还是更新
     * @param jdbcTemplate
     * @param sql
     * @param params
     * @param type
     * @param res
     */
    private void byCaseInvoke(JdbcTemplate jdbcTemplate, String sql,
                              Object[] params, Short type, PlatformResponse res){
        if (type == 0) {
            res.data(jdbcTemplate.queryForList(sql, params));
        } else {
            res.data(jdbcTemplate.update(sql, params));
        }
    }
}
